package com.caocaog.market.controller;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.caocaog.market.entity.ShopBasic;
import com.caocaog.market.entity.ShopCategory;
import com.caocaog.market.service.IShopBasicService;
import com.caocaog.market.service.IShopCategoryService;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * 店内分类
 *
 * @author guofeiyan
 * @date 2021-11-19
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(value = "shopCategory", tags = "店内分类")
@RequestMapping("/shop/shopCategory")
public class ShopCategoryController extends JeecgController<ShopCategory, IShopCategoryService> {
    @Autowired
    private IShopCategoryService shopCategoryService;
    @Autowired
    private CommonAPI commonAPI;
    @Autowired
    private IShopBasicService shopBasicService;

    /**
     * 分页列表查询
     *
     * @param shopCategory
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "店内分类-分页列表查询")
    @ApiOperation(value = "店内分类-分页列表查询", notes = "店内分类-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(ShopCategory shopCategory,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<ShopCategory> queryWrapper = QueryGenerator.initQueryWrapper(shopCategory, req.getParameterMap());
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (oConvertUtils.isNotEmpty(loginUser.getUserType()) && 1 != loginUser.getUserType()) {
            LambdaQueryWrapper<ShopBasic> shopQuery = new LambdaQueryWrapper<>();
            if (2 == loginUser.getUserType()) {

                //分站
                String siteId = loginUser.getSiteId();
                //获取商户ids
                List<String> merchantIds = commonAPI.findMerchantForSite(siteId);
                //获取门店
                if (oConvertUtils.listIsNotEmpty(merchantIds)) {
                    shopQuery.in(ShopBasic::getMerchantId, merchantIds);
                    List<String> shopIds = shopBasicService.list(shopQuery).stream().map(ShopBasic::getId).collect(Collectors.toList());
                    if (oConvertUtils.listIsNotEmpty(shopIds)) {
                        queryWrapper.in("shop_id", shopIds);
                    }
                }

            } else if (3 == loginUser.getUserType()) {
                //商户
                String merchantId = loginUser.getMerchantId();
                //获取门店
                if (oConvertUtils.isNotEmpty(loginUser.getCurrentSelectedShopId())) {
                    queryWrapper.in("shop_id", loginUser.getCurrentSelectedShopId());
                } else {
                    shopQuery.eq(ShopBasic::getMerchantId, merchantId);
                    List<String> shopIds = shopBasicService.list(shopQuery).stream().map(ShopBasic::getId).collect(Collectors.toList());
                    if (oConvertUtils.listIsNotEmpty(shopIds)) {
                        queryWrapper.in("shop_id", shopIds);
                    }
                }

            }
        }
        Page<ShopCategory> page = new Page<ShopCategory>(pageNo, pageSize);
        IPage<ShopCategory> pageList = shopCategoryService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param shopCategory
     * @return
     */
    @AutoLog(value = "店内分类-添加")
    @ApiOperation(value = "店内分类-添加", notes = "店内分类-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody ShopCategory shopCategory) {
        if (oConvertUtils.isEmpty(shopCategory.getName()) || oConvertUtils.isEmpty(shopCategory.getShopId())) {
            return Result.error("参数错误~");
        }
        //check 该门店内的分类是否重复
        ShopCategory shopCategoryCheck = shopCategoryService.getOne(new QueryWrapper<ShopCategory>().eq("shop_id", shopCategory.getShopId())
                .eq("name", shopCategory.getName()));
        if (oConvertUtils.isNotEmpty(shopCategoryCheck)) {
            return Result.error("该门店已有该分类[" + shopCategory.getName() + "],请勿重复添加哟~");
        }
        shopCategoryService.save(shopCategory);
        return Result.OK("添加成功！",true);
    }

    /**
     * 编辑
     *
     * @param shopCategory
     * @return
     */
    @AutoLog(value = "店内分类-编辑")
    @ApiOperation(value = "店内分类-编辑", notes = "店内分类-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody ShopCategory shopCategory) {
        if (oConvertUtils.isEmpty(shopCategory.getId()) || oConvertUtils.isEmpty(shopCategory.getName())
                || oConvertUtils.isEmpty(shopCategory.getShopId())) {
            return Result.error("参数错误~");
        }
        //check 该门店内的分类是否重复
        ShopCategory shopCategoryCheck = shopCategoryService.getOne(
                new QueryWrapper<ShopCategory>().eq("shop_id", shopCategory.getShopId())
                        .eq("name", shopCategory.getName()));
        if (oConvertUtils.isNotEmpty(shopCategoryCheck) && !shopCategory.getId().equals(shopCategoryCheck.getId())) {
            return Result.error("该门店已有该分类[" + shopCategory.getName() + "],请勿重复添加哟~");
        }
        shopCategoryService.updateById(shopCategory);
        return Result.OK("编辑成功!",true);
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "店内分类-通过id删除")
    @ApiOperation(value = "店内分类-通过id删除", notes = "店内分类-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        shopCategoryService.removeById(id);
        return Result.OK("删除成功!",true);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "店内分类-批量删除")
    @ApiOperation(value = "店内分类-批量删除", notes = "店内分类-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.shopCategoryService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!",true);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "店内分类-通过id查询")
    @ApiOperation(value = "店内分类-通过id查询", notes = "店内分类-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        ShopCategory shopCategory = shopCategoryService.getById(id);
        if (shopCategory == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(shopCategory);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param shopCategory
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ShopCategory shopCategory) {
        return super.exportXls(request, shopCategory, ShopCategory.class, "店内分类");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ShopCategory.class);
    }

}
